package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"
)

var addr = flag.String("addr", ":1234", "http service address")

func home(w http.ResponseWriter, r *http.Request) {
	log.Println(r.URL)
	if r.URL.Path != "/" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	fmt.Fprintf(w, "ws")
}

func stats(hub *Hub,w http.ResponseWriter, r *http.Request) {
    curNum := len(hub.clients)
	fmt.Fprintf(w, "当前在线人数:"+strconv.Itoa(curNum))
}

func main() {
	flag.Parse()
	hub := newHub()
	go hub.run()

	http.HandleFunc("/", home)
	http.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
		stats(hub,w,r)
	})
	//http.HandleFunc("/ws", echo)
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		serveWs(hub, w, r)
	})

	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
